package com.ajhlp.android.savecode.db;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import com.ajhlp.android.savecode.model.ConfigModel;


import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class ConfigOpenHelper extends SQLiteOpenHelper {
	private static final int DATABASE_VERSION = 1;
    private static final String CONFIG_TABLE_NAME = "t_config";
    public static final String KEY_NAME = "config_name";
    public static final String KEY_NUMBER = "target_num";
    public static final String KEY_CONTENT = "post_content";
    public static final String KEY_COUNT = "post_count";
    public static final String KEY_LASTEDIT = "last_edit";
    private static final String CONFIG_TABLE_CREATE =
                "CREATE TABLE " + CONFIG_TABLE_NAME + " (" +
                KEY_NAME + " TEXT, " +
                KEY_NUMBER + " TEXT, " +
                KEY_CONTENT + " TEXT, " +
                KEY_COUNT + " NUMBERIC, " +
                KEY_LASTEDIT + " TEXT);";

    public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	public ConfigOpenHelper(Context context) {
		super(context, CONFIG_TABLE_NAME, null, DATABASE_VERSION);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		db.execSQL(CONFIG_TABLE_CREATE);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
		// TODO Auto-generated method stub
		db.execSQL("DROP TABLE IF EXISTS "+ CONFIG_TABLE_NAME);
		db.execSQL(CONFIG_TABLE_CREATE);
	}
	
	public void deleteConfig(com.ajhlp.android.savecode.model.ConfigModel configModel) throws Exception{
		SQLiteDatabase db = getDB();
		
		try {
			db.execSQL("delete from " + CONFIG_TABLE_NAME + " where " + KEY_NUMBER +"='" + configModel.getTarget_num() + "' and "
							+KEY_CONTENT+"='"+configModel.getPost_content()+"'");
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw e;
		} finally {
			db.close();
		}
	}

	public void saveConfig(ConfigModel configModel) throws Exception{
		SQLiteDatabase db = getDB();
		
		try {
			Cursor cursor = db.rawQuery("select count(*) from " + CONFIG_TABLE_NAME + " where " + KEY_NUMBER +"='" + configModel.getTarget_num() + "' and "
							+KEY_CONTENT+"='"+configModel.getPost_content()+"'", null);
			
			if(cursor.moveToNext()){
				int count = cursor.getInt(0);
				
				Log.d("db", "count num is "+count);
				
				if(count > 0){
					throw new RuntimeException("this number["+configModel.getTarget_num()+"] is exist");
				}
			}
			
			db.execSQL("insert into "+CONFIG_TABLE_NAME+" ("+KEY_NAME+","+KEY_NUMBER+","+KEY_CONTENT+","+KEY_COUNT+","+KEY_LASTEDIT+
					") values ('"+configModel.getConfig_name()+"','"+configModel.getTarget_num()+"','"+configModel.getPost_content()+"'," +
					configModel.getCount()+","+configModel.getLast_edit()+")");
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw e;
		} finally {
			db.close();
		}
		
		
	}
	
	public List<ConfigModel> searchAllConfig(){
		List<ConfigModel> configs = new ArrayList<ConfigModel>();
		SQLiteDatabase db = null;
		try {
			db = getDB();
			Cursor cursor = db.rawQuery("select "+KEY_NAME+","+KEY_NUMBER+","+KEY_CONTENT+","+KEY_COUNT+","+KEY_LASTEDIT+" from "+CONFIG_TABLE_NAME+" order by "+KEY_LASTEDIT+" desc", null);
			while(cursor.moveToNext()){
				ConfigModel configModel = new ConfigModel();
				configModel.setConfig_name(cursor.getString(0));
				configModel.setTarget_num(cursor.getString(1));
				configModel.setPost_content(cursor.getString(2));
				configModel.setCount(cursor.getInt(3));
				configModel.setLast_edit(cursor.getLong(4));
	            configs.add(configModel);  
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			
		} finally {
			if(db != null){
				db.close();
			}
		}
		return configs;
	}
	
	public void updateConfig(ConfigModel configModel) throws Exception{
		SQLiteDatabase db = getDB();
		
		try {
			
			db.execSQL("update "+CONFIG_TABLE_NAME+" set "+
						KEY_COUNT+"="+configModel.getCount()+","+
						KEY_LASTEDIT+"="+System.currentTimeMillis()+
						" where " +
						KEY_NUMBER + "='"+configModel.getTarget_num()+"' and "+
						KEY_CONTENT + "='" + configModel.getPost_content() + "'");
			
		} catch (Exception e) {
			// TODO: handle exception
			throw e;
		} finally {
			db.close();
		}
	}
	
	public SQLiteDatabase getDB() throws NullPointerException{
		SQLiteDatabase db = getWritableDatabase();
		
		if(db == null){
			throw new NullPointerException("can't get db");
		}
		
		return db;
	}
}
